Imports Microsoft.VisualBasic
Imports System
Imports System.Configuration
Imports System.IO
Imports System.Security.Permissions
Imports System.Collections
Imports System.Diagnostics
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Security
Imports System.ComponentModel
Imports Microsoft.Win32

<Assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, All := "HKEY_CURRENT_USER")>

Namespace Phoenix.Tools.Backup
	Public Class OperationManager
		Public BackupMode As Boolean = True
        Public AttachMode As Boolean = False
        Public DBOnly As Boolean = False
		Public DBUsername As String = Nothing
		Public DBPassword As String = Nothing
		Public DBDatabase As String = Nothing
		Public DBWindowAuthentication As Boolean = True
		Public DBServer As String = Nothing
		Public BackupFile As String = Nothing
		Public BackupDirectory As String = Nothing
		Public DatabaseUser As String = "Phoenix"
		Public LoginName As String = "Phoenix"
		Private preferencesName As String = ConfigurationSettings.AppSettings("PreferencesDirectory")
		Private configName As String = ConfigurationSettings.AppSettings("ConfigFileName")
		Private ExecutablePath As String = Path.GetDirectoryName(Application.ExecutablePath)

		Public Sub ExecuteOperation()
			ExecuteOperation(True)
		End Sub

		Public Sub TestPipe()
			Try
			Catch e As Exception
				MessageBox.Show(e.ToString())
			End Try
			'''
		End Sub

		Private showGui As Boolean
		Public Sub ExecuteOperation(ByVal showGui As Boolean)
			Try
                Me.showGui = showGui
                If AttachMode Then
                    DoAttach()
                ElseIf BackupMode Then
                    DoBackup()
                Else
                    DoRestore()
                End If
            Catch e As Exception
				MessageBox.Show(e.Message)
			End Try
		End Sub

        Private Sub DoBackup()
            If (Not Directory.Exists(BackupDirectory)) Then
                Directory.CreateDirectory(BackupDirectory)
            End If

            If (Not DBOnly) Then
                CopyFiles(True)
            End If

            If File.Exists(BackupFile) Then
                File.Delete(BackupFile)
            End If

            Dim backup As SQLDMO.BackupClass = New SQLDMO.BackupClass
            backup.Initialize = True
            backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database
            backup.Database = DBDatabase
            backup.BackupSetName = "Phoenix"
            backup.Files = "[" & BackupFile & "]"
            backup.PercentCompleteNotification = 10
            AddHandler backup.PercentComplete, AddressOf OnProgress
            backup.SQLBackup(GetSQLServer())
        End Sub

        Private Sub CopyFiles(ByVal isBackup As Boolean)
            If isBackup Then
                If File.Exists(Path.Combine(ExecutablePath, configName)) Then
                    File.Copy(Path.Combine(ExecutablePath, configName), Path.Combine(BackupDirectory, configName), True)
                End If

                Dim source As String = Path.Combine(ExecutablePath, preferencesName)
                Dim dest As String = Path.Combine(BackupDirectory, preferencesName)
                CopyDirectory(source, dest)
            Else
                If File.Exists(Path.Combine(BackupDirectory, configName)) Then
                    File.Copy(Path.Combine(BackupDirectory, configName), Path.Combine(ExecutablePath, configName), True)
                End If

                Dim source As String = Path.Combine(BackupDirectory, preferencesName)
                Dim dest As String = Path.Combine(ExecutablePath, preferencesName)
                CopyDirectory(source, dest)
            End If
        End Sub

        Private Sub CopyDirectory(ByVal source As String, ByVal dest As String)
            Dim files As String() = Directory.GetFiles(source)
            For Each f As String In files
                If (Not Directory.Exists(dest)) Then
                    Directory.CreateDirectory(dest)
                End If

                File.Copy(f, Path.Combine(dest, Path.GetFileName(f)), True)
            Next f
            Dim dirs As String() = Directory.GetDirectories(source)
            For Each dir As String In dirs
                Dim destDir As String = dest & dir.Replace(source, "")
                CopyDirectory(dir, destDir)
            Next dir
        End Sub

        Private Sub DoAttach()
            Dim sql As SQLDMO.SQLServerClass = GetSQLServer()
            sql.AttachDB(DBDatabase, "[" & BackupFile & "]")
        End Sub


        Private Sub DoRestore()
            If (Not DBOnly) Then
                CopyFiles(False)
            End If

            Dim sql As SQLDMO.SQLServerClass = GetSQLServer()
            Dim restore As SQLDMO.RestoreClass = New SQLDMO.RestoreClass
            restore.ReplaceDatabase = True
            restore.Database = DBDatabase
            restore.Files = "[" & BackupFile & "]"
            restore.PercentCompleteNotification = 10
            AddHandler restore.PercentComplete, AddressOf OnProgress
            restore.SQLRestore(sql)
        End Sub

        Public Sub SetDefaultDatabseSettings()
            Me.DBPassword = "gfhjkmCF"
            Me.DBDatabase = "Phoenix"
            Me.DBServer = Environment.MachineName & "\Phoenix"
            Me.DBUsername = "sa"
        End Sub

        Private Sub OnProgress(ByVal s As String, ByVal percent As Integer)
        End Sub

        Public Sub SaveUserPreferences()
            If showWelcomePage_Renamed Is Nothing Then
                showWelcomePage_Renamed = True
            End If
            Try
                'INSTANT VB NOTE: The following 'using' block is replaced by its pre-VB.NET 2005 equivalent:
                '				using(RegistryKey key = Registry.CurrentUser.OpenSubKey(_registryPath, True))
                Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_registryPath, True)
                Try
                    If key Is Nothing Then
                        CreateKey()
                    Else
                        key.SetValue(_regShowWelcome, IIf((showWelcomePage_Renamed.Equals(True)), 1, 0))
                        key.SetValue(_regDefaultPath, _defaultPath)
                    End If
                Finally
                    If TypeOf key Is IDisposable Then
                        Dim disp As IDisposable = key
                        disp.Dispose()
                    End If
                End Try
                'INSTANT VB NOTE: End of the original C# 'using' block
            Catch e As Exception
                Debug.Write(e)
            End Try
        End Sub

        Private Sub CreateKey()
            'INSTANT VB NOTE: The following 'using' block is replaced by its pre-VB.NET 2005 equivalent:
            '			using(RegistryKey key = Registry.CurrentUser.CreateSubKey(_registryPath))
            Dim key As RegistryKey = Registry.CurrentUser.CreateSubKey(_registryPath)
            Try
                key.SetValue(_regShowWelcome, IIf((showWelcomePage_Renamed.Equals(True)), 1, 0))
                key.SetValue(_regDefaultPath, _defaultPath)
            Finally
                If TypeOf key Is IDisposable Then
                    Dim disp As IDisposable = key
                    disp.Dispose()
                End If
            End Try
            'INSTANT VB NOTE: End of the original C# 'using' block
        End Sub

        Public Property ShowWelcomePage() As Boolean
            Get
                If showWelcomePage_Renamed Is Nothing Then
                    Try
                        'INSTANT VB NOTE: The following 'using' block is replaced by its pre-VB.NET 2005 equivalent:
                        '						using(RegistryKey key = Registry.CurrentUser.OpenSubKey(_registryPath))
                        Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_registryPath)
                        Try
                            showWelcomePage_Renamed = (CInt(key.GetValue(_regShowWelcome, 1))) <> 0
                        Finally
                            If TypeOf key Is IDisposable Then
                                Dim disp As IDisposable = key
                                disp.Dispose()
                            End If
                        End Try
                        'INSTANT VB NOTE: End of the original C# 'using' block
                    Catch
                        showWelcomePage_Renamed = True
                    End Try
                End If
                Return CBool(showWelcomePage_Renamed)
            End Get
            Set(ByVal Value As Boolean)
                showWelcomePage_Renamed = Value
            End Set
        End Property

        Public Function ListServers() As String()

            Dim servers As SQLDMO.NameList = GetDMOApplication().ListAvailableSQLServers()
            Dim ss As ArrayList = New ArrayList

            For Each name As String In servers
                If name = "(local)" Then
                    GoTo Continue1
                End If
                ss.Add(name)
Continue1:
            Next name
            Return CType(ss.ToArray(GetType(String)), String())
        End Function

        Public Function ListDatabases() As String()
            Dim ss As ArrayList = New ArrayList
            Dim server As SQLDMO.SQLServerClass = GetSQLServer()
            Try
                Dim dbList As SQLDMO.Databases = server.Databases
                For Each db As SQLDMO.Database In dbList
                    ss.Add(db.Name)
                Next db

            Finally
                server.DisConnect()
            End Try

            Return CType(ss.ToArray(GetType(String)), String())
        End Function

        Private Function GetDMOApplication() As SQLDMO.ApplicationClass
            Return New SQLDMO.ApplicationClass
        End Function

        Private Function GetSQLServer() As SQLDMO.SQLServerClass
            Dim server As SQLDMO.SQLServerClass = New SQLDMO.SQLServerClass

            If DBWindowAuthentication Then
                Try
                    server.Start(False, DBServer, Nothing, Nothing)
                Catch

                End Try

                server.LoginSecure = True
                server.Connect(DBServer, Nothing, Nothing)
            Else
                Try
                    server.Start(False, DBServer, Nothing, Nothing)
                Catch

                End Try
                server.LoginSecure = False
                server.Connect(DBServer, DBUsername, DBPassword)
            End If
            Return server
        End Function

        Public Property DefaultPath() As String
            Get
                If _defaultPath Is Nothing Then
                    Try
                        Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_registryPath)
                        Try
                            _defaultPath = key.GetValue(_regDefaultPath, String.Empty)
                        Finally
                            If TypeOf key Is IDisposable Then
                                Dim disp As IDisposable = key
                                disp.Dispose()
                            End If
                        End Try
                    Catch
                        _defaultPath = String.Empty
                    End Try
                End If
                Return _defaultPath
            End Get
            Set(ByVal Value As String)
                _defaultPath = Value
            End Set
        End Property


        Private showWelcomePage_Renamed As Object = Nothing
        Private _defaultPath As String
        Private Shared _registryPath As String = "SOFTWARE\Phoenix\BackupWizard"
        Private Shared _regShowWelcome As String = "ShowWelcome"
        Private Shared _regDefaultPath As String = "Folder"
    End Class
End Namespace
